/**
 * Dwr-backed State provider.  
 Usage:  
 new Ext.state.DwrStateProvider(MyDwrProxy.mySetFunction,MyDwrProxy.myClearFunction);


Each function should implement the signiture: 
myFunction(String userId, String settingName, String settingValue) 

 
**/


Ext.state.DwrStateProvider = function(options){
	this.setFunc=options.setFunction;
	this.getFunc=options.getFunction;
	this.clearFunc=options.clearFunction;
	this.pageId = options.pageId||document.location.pathname;
	// bulk load support	
	this.bulkLoadFunc=options.bulkLoadFunction||false;
	this.bulkLoadedKeys = options.preLoadedValues|| {};
	this.bulkLoaded= options.preLoadedValues!==null;
	// preload the data
	this.loadState();	
	
	this.changeQueue=[];
    Ext.state.DwrStateProvider.superclass.constructor.call(this);
 };

Ext.extend(Ext.state.DwrStateProvider, Ext.state.Provider, {
		loadState: function() {
			var stateMgr = this;
			this.bulkLoadFunc.apply(this,[this.pageId,{async:false,callback:function(stateMap) {
				stateMgr.state=stateMap;
				stateMgr.bulkLoaded=true;
			}}]);
		},
	// private
		set : function(name, value) {
			console.log('Set:'+name+' - '+value);
			
			//if (name.length>3 && name.substr(0,3)=='ext') return;
			
			if (typeof value == "undefined" || value === null) {
				this.clear(name);
				return;
			}
			var o = {
				pageId : this.pageId,
				code : name,
				value : this.encodeValue(value)
			};
			this.changeQueue.push(o);
			//console.log('Set:'+name+' - '+o.value);
			var args = [this.pageId,o.code,o.value,Ext.emptyFn()];
			this.setFunc.apply(this,args);
			Ext.state.DwrStateProvider.superclass.set.call(this, name, value);
		},

		// private
		clear : function(name) {
			console.log('Clear:'+name);
			var o = {
				userId : this.userId,
				code : name,
				value : ''
			};
			this.changeQueue.push(o);
			var args = [this.pageId,o.code];
			this.clearFunc.apply(this,args);
			Ext.state.DwrStateProvider.superclass.clear.call(this, name);
		},
		bulkSave:function() {
			dwr.engine.beginBatch();
			
			dwr.engine.executeBatch();
		},
		// private
		get : function(name, defaultValue) {
			//if (name.length>3 && name.substr(0,3)=='ext') return undefined;
			//debugger;
			var result;
		if(this.bulkLoaded) {
			 result = this.bulkLoadedKeys[name];			
		} else {
			var args = [this.pageId,name,{async:false, callback:function(retValue) {
			   result = retValue;
			}}];
			this.getFunc.apply(this,args);
		}
		 console.log('Get:'+name +'('+result+')');
			if (!result) {
				this.set(name, defaultValue);
				return this.decodeValue(defaultValue);
			}
			return this.decodeValue(result.value);
		}

});
		
Ext.override(Ext.Component,{
   //stateful:false
}); //Thanks: http://extjs.com/forum/showthread.php?t=15675

